<?php
namespace app\common\service;
use app\common\xunfei\XFTrans;
use think\Exception;
use think\facade\Db;
use app\common\model\WordDict as WordDictModel;
use app\common\model\UserFavorWord as UserFavorWordModel;


/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/21 0021
 * Time: 15:44
 */
class WordService{

    /**
     * 添加单词到生词本
     * @param $word
     * @return array|null|\think\Model|static
     */
    public function addWordToDict($word){
        //查找单词是否在 字典中 如果不在则添加
        $data = Db::table("word_dict")->where(['word'=>$word])->find();
        if(empty($data)){

            //获取该单词的翻译
            $cn = $this->trans($word);
            $data = [
                'word'=>$word,
                'cn'=>$cn
            ];
            return WordDictModel::create($data);
        }
        return $data;
    }


    /**
     * 获取单词翻译
     * @param $word
     * @return string
     */
    public function trans($word){
        $xunfei = new XFTrans();
        $res = $xunfei->xfyun($word);
        $res = json_decode($res,true);
        if($res['message'] == 'success'){
            return $res['data']['result']['trans_result']['dst'];
        }else{
            return "";
        }
    }


    /**
     * 添加单词到我的生词本
     */
    public function addWordToFavor( $word, $uid, $videoId ){
        $wordModel = $this->addWordToDict($word);

        //只要根据用户和单词来排重
        $count = Db::table('user_favor_word')->where([
            'uid'=>$uid,
            'word_id'=>$wordModel['id']
        ])->count();

        if($count){
            throw new \Exception("该单词已经收藏了");
        }
        $data = [
            'video_id'=>$videoId,
            'uid'=>$uid,
            'word_id'=>$wordModel['id']
        ];

        UserFavorWordModel::create($data);
    }



    public function wordsByVideo($videoId,$uid,$page=1,$pageSize=20){
        $start = ($page-1) * $pageSize;
        $where = [
            'uid'=>$uid,
            'video_id'=>$videoId
        ];
        $list = Db::table('user_favor_word')->where($where)->limit($start,$pageSize)->order('id','desc')->select()->toArray();
        $count = Db::table('user_favor_word')->where($where)->count();

        $wordIds = [];
        foreach( $list as $key => $val ){
            array_push($wordIds,$val['word_id']);
        }

        $words = Db::table('word_dict')->whereIn('id',$wordIds)->column('word,cn','id');
        foreach( $list as $key => $val ){
            $list[$key]['word'] = $words[$val['word_id']];
        }
        return ['list'=>$list,'total'=>$count];
    }

}